package com.example.administrator.bdsjws;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

import com.example.administrator.bdsjws.com.Constants;
import com.example.administrator.bdsjws.db.BBXDao;
import com.example.administrator.bdsjws.db.DaoMaster;
import com.example.administrator.bdsjws.db.DaoSession;
import com.example.administrator.bdsjws.utils.MyUtil;
import com.example.administrator.bdsjws.vo.BBX;
import com.socks.library.KLog;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.greendao.database.Database;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;


public class MyApplication extends Application {
    //功能：1、提供全局的上下文 2、初始化KLOG

    static Context context;
    static DaoSession daoSession;
    boolean aaa=true;
//真正的入口方法
    @Override
    public void onCreate() {
        super.onCreate();
        context=getApplicationContext();
        KLog.init(aaa, Constants.LOG_FLAG);
        initokhttpclient();
        initDatabase();
        initDatatoTable();
    }

    public void initokhttpclient(){
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .addInterceptor(new LoggerInterceptor("TAG"))
                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                .readTimeout(10000L, TimeUnit.MILLISECONDS)
                //其他配置
                .build();

        OkHttpUtils.initClient(okHttpClient);
    }

    public static Context getContext(){

        return context;
    }

    private static void initDatabase(){
        DaoMaster.DevOpenHelper  openHelper=new DaoMaster.DevOpenHelper(context,Constants.DATABASE_NAME);
        Database database=openHelper.getWritableDb();
        DaoMaster daoMaster=new DaoMaster(database);
        daoSession=daoMaster.newSession();
    }

    public static DaoSession getDaoSession(){
        return daoSession;
    }


    public void initDatatoTable(){
        DaoSession daoSession=getDaoSession();
        BBXDao bbxDao=daoSession.getBBXDao();

        SharedPreferences sharedPreferences= MyUtil.getSharedPre();
        boolean b=sharedPreferences.getBoolean("inserttable",false);
        if (!b){
            String[] names=getResources().getStringArray(R.array.bbx_name);
            String[] icons=getResources().getStringArray(R.array.bbx_icon);

            for (int i=0;i<names.length;i++){
                BBX bbx = new BBX(null,names[i],icons[i]);
                try {
                    long m=bbxDao.insert(bbx);
                    if (m>0){
                        KLog.i("新增成功");
                    }else{
                        KLog.i("新增失败");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            SharedPreferences.Editor editor=sharedPreferences.edit();
            editor.putBoolean("inserttable",true);
            editor.commit();
        }else{

        }

    }


}
